package com.wisdytech.linkdcs.system.action;


import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.handler.ResourceMatchingService;
import com.wisdytech.common.session.UserSession;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DataTransformUtil;
import com.wisdytech.common.utils.ExcelUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.system.service.ISystemUserService;
import com.wisdytech.linkdcs.system.vo.UserUpdateVO;
import com.wisdytech.linkdcs.system.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 
 * <p>
 * ClassName: SystemUserAction.java
 * </p>
 * <p>
 * Description: 
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-13
 * </p>
 */
@Controller
@RequestMapping("/system/user")
public class SystemUserAction  {
	//无权限跳转url
    @RequestMapping("/unauthorized")
    public String unauthorized(Model model){
        return "error/error";
    }
	
	
    private static final Logger logger = LoggerFactory.getLogger(SystemUserAction.class);
    /**
     * 员工service
     */
    @Autowired
    @Qualifier("systemUserService")
    private ISystemUserService systemUserService;

    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;
    @RequestMapping("/index")
    public String index(Model model, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "system/user/userIndex";
    }
    
    /**
     * 
     * @param username 用户名
     * @param truename 姓名
     * @param workNo 工号
     * @param filter 分页参数
     * @return 用户管理列表信息
     * @throws IOException 
     */
    @RequestMapping(value = "/listSysUser/get.mvc")
    @ResponseBody
    public StandardTableResult<UserVO> getStandardTableResult(String username, String truename, String workNo, Filter filter) throws IOException{
    	PageInfo<SysUser> users =this.systemUserService.listSysUsers(username,truename,workNo, filter);
        //转换为前台结果集
        List<SysUser> userList=users.getList();
        List<UserVO> userVOList=new ArrayList<UserVO>();
        for(SysUser sysUser:userList){
            userVOList.add(DataTransformUtil.changeUser2UserVO(sysUser));
        }
        return new StandardTableResult<UserVO>(users.getTotal(),userVOList);
    }
    
    /**
     * 
     * @param username 用户名
     * @param truename 姓名
     * @param workNo 工号
     * @param filter 分页参数
     * @return 用户管理列表信息
     * @throws IOException 
     */
    @RequestMapping(value = "/listAllUser/get.mvc")
    @ResponseBody
    public StandardResult getUserLists(String username, Filter filter) throws IOException{
    	PageInfo<SysUser> users =this.systemUserService.listSysUsers(username,"","", filter);
        //转换为前台结果集
        List<SysUser> userList=users.getList();
        List<UserVO> userVOList=new ArrayList<UserVO>();
        for(SysUser sysUser:userList){
            userVOList.add(DataTransformUtil.changeUser2UserVO(sysUser));
        }
        
      //判断是否是最后一页
        if(filter.getNum()>=users.getPages()){
            return StandardResult.getFailResult("",userVOList);
        }else{
            return StandardResult.getSuccessResult(userVOList);
        }
    }
    
    
    
    /**
     * <p>Description: 点击修改时带出对应用户信息</p> 
     * @param pkId 用户唯一标识id
     * @return 用户对象
     */
    @RequestMapping(value = "/getUserById/get.mvc")
    @ResponseBody
    public UserUpdateVO getUserById(String pkId){
        SysUser user = systemUserService.getUserById(pkId);
        UserUpdateVO userUpdateVO=new UserUpdateVO();
        userUpdateVO = DataTransformUtil.changeUser2UserUpdateVO(user);
        return userUpdateVO;
    }
    /**
     * <p>Description: 删除用户信息</p> 
     * @param pkId 用户唯一标识id
     * @return boolean值
     */
    @RequestMapping(value = "/delSysUserById/del.mvc")
    @ResponseBody
    public StandardResult delSysUserById(String pkId) {
        return systemUserService.deleteUserById(pkId);
    }
    
    /**
     * <p>Description: 禁用用户</p> 
     * @param pkId 用户唯一标识id
     * @return 标准返回值对象
     */
    @RequestMapping(value = "/disableUserById/disable.mvc")
    @ResponseBody
    public StandardResult disableUserById(String pkId) {
        return systemUserService.disableUserById(pkId);
    }
    /**
     * <p>Description: 启用用户</p> 
     * @param pkId 用户唯一标识id
     * @return 标准返回值对象
     */
    @RequestMapping(value = "/enableUserById/enable.mvc")
    @ResponseBody
    public StandardResult enableUserById(String pkId) {
        return systemUserService.enableUserById(pkId);
    }
    
    /**
     * <p>Description: 保存用户</p> 
     * @param sysUser 用户唯一标识id
     * @return 标准返回值对象
     */
    @RequestMapping(value = "/saveUser/save.mvc")
    @ResponseBody
    public StandardResult saveUser(SysUser sysUser,HttpSession session) {
        UserSession userSession = BaseUtil.getUserSession(session);
        //0-代表用户被禁用
        if (StringUtils.isBlank(sysUser.getEnabled())) {
            sysUser.setEnabled("0");
        }
        if (StringUtils.isBlank(sysUser.getPkId())) {
            return systemUserService.addSysUser(sysUser,userSession);
        }else {
            return systemUserService.updateUser(sysUser);
        }
    }
    
    /**
     * <p>Description: 导出用户信息</p>
     * @param request 请求对象
     * @param response 返回对象
     * @throws Exception 异常
     */
    @RequestMapping(value = "/exportUser/export.mvc")
    public void exportData(HttpServletRequest request, HttpServletResponse response, Filter filter) throws Exception {
        SimpleDateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String[] columnNames = null;
        String[] fileNames = null;
        String fileName = "用户信息";
        String username = request.getParameter("username");
        String truename = request.getParameter("truename");
        System.out.println(truename);
        String workNo = request.getParameter("workNo");
        filter.setSize(65535);
        PageInfo<SysUser> users;
        users = systemUserService.listSysUsers(username,truename,workNo, filter);
        List<SysUser> userList=users.getList();
        for (SysUser sysUser : userList) {
            if ("0".equals(sysUser.getEnabled())) {
                sysUser.setEnabled("否");
            }else {
                sysUser.setEnabled("是");
            }
        }
        String finalFileName = null;  
        final String userAgent = request.getHeader("USER-AGENT"); 
        if(StringUtils.contains(userAgent, "MSIE")){
            //IE浏览器  
            finalFileName = URLEncoder.encode(fileName,"UTF8");  
        }else {
            finalFileName = fileName;
        }
        columnNames = new String[] { "工号", "姓名", "用户名", "角色", "是否启用", "联系电话", "手机", "联系地址", "邮箱地址",
                "创建日期","微信名" };
        fileNames = new String[] { "workNo", "truename", "username","roleNameStr",
                "enabled", "telephone", "mobile", "address", "email" , "createDate", "wechatName"};
        ExcelUtil.exportExcel(response, userList, SysUser.class, columnNames, fileNames,
                finalFileName + dateFormat.format(new Date()));
    }

    @RequestMapping(value = "/getSysUserList/get.mvc")
    @ResponseBody
    public StandardResult getSysUserList(@ModelAttribute("search") String search, Filter filter) {
        logger.info("search:{},filter:{}",search,String.valueOf(filter));
        PageInfo<SysUser> page = this.systemUserService.getSystemUserList(search,filter);
        return StandardResult.getSuccessResult(page.getList());
    }

    @RequestMapping(value = "/getCurrentUser/get.mvc")
    @ResponseBody
    public StandardResult getCurrentUser() {
        SysUser user = BaseUtil.getCurrentUser();
        return StandardResult.getSuccessResult(user);
    }

}
